package com.dao;

import com.model.Course;
import com.model.StuException;
import com.util.XmlUtil;
import org.dom4j.Document;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * Created by guin_guo on 2015/10/31.
 */
public class CourseDao {
    public final static String COURSE_XML = "courses.xml";
    private Document cd;

    private CourseDao() {
        cd = XmlUtil.getCourseDocument();
    }
    private static class Singleton{
        public static CourseDao instance = new CourseDao();
    }
    public static CourseDao getInstance(){
        return Singleton.instance;
    }

    private void write(){
        XmlUtil.write2XML(cd,COURSE_XML);
    }

    public void add(Course course) {
        Course c = this.loadByName(course.getName());
        if (c != null) {
            throw new StuException("要添加的课程已存在");

        }
        Element root = cd.getRootElement();
        Element cs   = root.addElement("course");
        cs.addAttribute("id",String.valueOf(XmlUtil.getMaxId(cd,"/courses/course")+1));
        cs.addElement("sid").addText(course.getSid() + "");
        cs.addElement("tid").addText(course.getTid()+"");
        cs.addElement("student").addText(course.getStudent());
        cs.addElement("teacher").addText(course.getTeachet());
        cs.addElement("name").addText(course.getName());
        cs.addElement("place").addText(course.getPlace());
        cs.addElement("time").addText(course.getTime());
        write();
    }

    public Course loadByName(String name) {
        String path = "/courses/course[name='"+name+"']";
        Element course = (Element)cd.selectSingleNode(path);
        if(course==null){
            return null;
        }
        Course c = new Course();
        c.setId(Integer.parseInt(course.attributeValue("id")));
        c.setSid(Integer.parseInt(course.elementText("sid")));
        c.setTid(Integer.parseInt(course.elementText("tid")));
        c.setName(course.elementText("name"));
        c.setPlace(course.elementText("place"));
        c.setStudent(course.elementText("student"));
        c.setTeachet(course.elementText("teacher"));
        c.setTime(course.elementText("time"));
        return c;
    }

    /**
     * 获取所有的Course
     * @return List里面存放 Vector
     */
    public List<Vector> list() {
        String path = "/courses/course";
        List<Element> els = cd.selectNodes(path);
        List<Vector> list = new ArrayList<>(els.size());
        for (Element e : els) {
            Vector v = new Vector();
            v.add(e.attributeValue("id"));
            v.add(e.elementText("sid"));
            v.add(e.elementText("tid"));
            v.add(e.elementText("name"));
            v.add(e.elementText("place"));
            v.add(e.elementText("student"));
            v.add(e.elementText("teacher"));
            v.add(e.elementText("time"));
            list.add(v);
        }
        return list;
    }

}
